float4x4 gWVP;
float4x4 gView;
float4x4 gProj;
float3 gLightPos;
float3 gLightDir;
texture gTex0;
texture gTex1;
texture gTex2;
texture gTex3;

sampler tex0Sampler = sampler_state
{
	Texture = <gTex0>;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
	MipFilter = LINEAR;
	AddressU = WRAP;
	AddressV = WRAP;
};
sampler tex1Sampler = sampler_state
{
	Texture = <gTex1>;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
	MipFilter = LINEAR;
	AddressU = WRAP;
	AddressV = WRAP;
};
sampler tex2Sampler = sampler_state
{
	Texture = <gTex2>;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
	MipFilter = LINEAR;
	AddressU = WRAP;
	AddressV = WRAP;
};
sampler tex3Sampler = sampler_state
{
	Texture = <gTex3>;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
	MipFilter = LINEAR;
	AddressU = WRAP;
	AddressV = WRAP;
};
struct Output
{
	float4 posH   :POSITION0;
	float2 tex	  :TEXCOORD0;
	float2 texBlend:TEXCOORD1;
	float3 normal :TEXCOORD2;
};

Output TerrainVS(float3 posL:POSITION0,float3 normal:NORMAL0,float2 tex:TEXCOORD0,float2 texBlend:TEXCOORD1)
{
	Output outVert = (Output)0;
	outVert.posH = mul(float4(posL,1.0f),gWVP);
	outVert.tex = tex * 3;
	outVert.texBlend = texBlend;
	outVert.normal = normalize(normal); 
	return outVert;
}

float4 TerrainPS(float2 tex:TEXCOORD0,float2 texBlend:TEXCOORD1,float3 normal:TEXCOORD2):COLOR0
{
	float4 tex0Color = tex2D(tex0Sampler,tex);	
	float4 tex1Color = tex2D(tex1Sampler,tex);
	float4 tex2Color = tex2D(tex2Sampler,tex);
	float4 blendColor = tex2D(tex3Sampler,texBlend);
	float inverse = 1.0f/(blendColor.r + blendColor.g + blendColor.b);
	float rfactor= blendColor.r*inverse;
	float gfactor = blendColor.g*inverse;
	float bfactor = blendColor.b*inverse;
		
	float4 finalColor = tex0Color*rfactor+ tex1Color*gfactor+ tex2Color*bfactor;	

	float diffuseCoef = saturate( dot(normal, -gLightDir ) );
	float ambientCoef = 0.3f;
	finalColor = (diffuseCoef + ambientCoef)*finalColor;
	return finalColor;	
}

technique TerrainTech
{
	pass P0
	{
		vertexShader = compile vs_2_0 TerrainVS();	
		pixelShader = compile ps_2_0 TerrainPS();
		//FillMode = wireframe;
	}
}
